const fs = require('fs'); // 文件模块，用于改文件名字
var iconv = require('iconv-lite'); // 写文件 转码
var path = require('path');

const resultFormat = (code = 200, content = '', msg = 'null')=> {
    let result = { code: code, data: content, msg: msg };
    return result;
};
module.exports = function (app) {
    const prefix = '/api/blog/';
    const folder = '../../../www/blog/';
    // 博客提交
    app.post(prefix + 'submit', (req, res) => {
        var localPath = req.body.file;
        var buffer = iconv.encode(req.body.content, 'utf8'); // 这里调用encode函数进行转码
        var sourceFile = path.join(__dirname, folder, localPath + '.md');
        var destPath = path.join(__dirname, folder, localPath + '.' + (new Date).getTime() + '.md');
        var readStream = fs.createReadStream(sourceFile);
        var writeStream = fs.createWriteStream(destPath);
        readStream.pipe(writeStream);
        fs.writeFile(sourceFile, buffer, (error)=>{
            let result;
            if (error) {
                result = resultFormat(200, {res: 0, msg: error || 'failed'});
            } else {
                result = resultFormat(200, {res: 1, msg: 'success'});
            }
            res.end(JSON.stringify(result));
        });
    });
    // 同步读取博客文章
    app.get(prefix + 'read', (req, res) => {
        const localPath = req.query.file;
        // '--------开始读取文件--------'
        var sourceFile = path.join(__dirname, folder, localPath + '.md');
        const data = fs.readFileSync(sourceFile, 'utf-8');
        // '--------读取结束--------'
        const code = 200;
        const msg = '';
        const time = +(new Date);
        const result = {code, data, msg, time};
        return res.end(JSON.stringify(result));
    });
};
